package com.woniuxy.util;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

public class CheckTokenUtil {


    public static Map<String, Object> getUser(String token) {

        // 替换为实际的check_token接口地址
        String url = "http://localhost:8081/oauth/check_token?token=" + token;

        // 创建HttpClient实例
        HttpClient httpClient = HttpClients.createDefault();


        // 创建HttpGet请求，并添加token到请求头
        HttpPost httpGet = new HttpPost(url);
        // httpGet.setHeader("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjMsInVzZXJfbmFtZSI6InNhbGV3Iiwic2NvcGUiOlsiYWxsIl0sImV4cCI6MTY5NDQ5NDQyNSwiYXV0aG9yaXRpZXMiOlsic2FsZTphZGRDaG9vc2UiLCJzYWxldyIsInNhbGU6YWRkUGFjayIsInNhbGU6YWRkZEVwb3NpdExpc3QiLCJidXk6YWRkTmVlZCIsInNhbGU6YWRkVGFpbExpc3QiXSwianRpIjoiYThlZjU4YzYtYmIyYi00YjVjLWI4MDItN2QzOTliN2ZmODhkIiwiYWNjb3VudCI6InNhbGV3IiwiY2xpZW50X2lkIjoid29uaXV4eSJ9.DbEsVKSZnAaZg_i0LaqopR2vhtiK-Egvgb-tJt4BffE\"\n");


        try {
            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(httpGet);

            // 检查响应状态码，200表示成功
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析响应内容，这里假设返回的是JSON格式数据
                String json = EntityUtils.toString(response.getEntity());
                // System.out.println(json);
                String s = json;
                String a = json;
                s = json.substring(7, s.indexOf(",\"user"));
                // System.out.println("s:"+ s);
                int i = Integer.valueOf(s).intValue();
                a = a.substring(a.indexOf("\"user_name\""), a.indexOf("\"scope\""));
                //System.out.println("a:"+a);
                a = a.substring(13, a.indexOf("\","));
                // System.out.println("2a:"+a);
                Map<String, Object> map = new HashMap<>();
                map.put("uid", i);
                map.put("account", a);
                return map;
                // 根据实际数据结构处理结果，例如：
                // String result = json.get("result");
                // System.out.println("Check token result: " + json);

            } else {
                // System.out.println("Error: " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
